package org.example.springcloud.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import net.minidev.json.JSONObject;
import org.example.springcloud.bean.PageResult;
import org.example.springcloud.bean.RequestParam;
import org.example.springcloud.bean.ResponseResult;
import org.example.springcloud.entities.User;
import org.example.springcloud.service.IUserService;
import org.example.springcloud.util.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private DruidDataSource dataSource;


    @CrossOrigin("*")
    @RequestMapping(value = "/list")
    public ResponseResult<PageResult<User>> getList(@RequestBody JSONObject jsonObject) throws JsonProcessingException {
        System.out.println("json:" + jsonObject);
        //json转对象
        RequestParam<User> pageParam = JacksonUtil.fromJson(jsonObject.toJSONString(), new TypeReference<RequestParam<User>>() {});
        PageResult<User> pageBean = userService.getList(pageParam.getPageParam());
        System.out.println(pageBean);
        return ResponseResult.success(200, "success", pageBean);
    }

    @RequestMapping(value="/get/{id}",method= RequestMethod.GET)
    public User get(@PathVariable("id")Long userId) {
        User user = userService.getUser(userId);
        return user;
    }

    @RequestMapping(value="/add",method=RequestMethod.POST)
    public boolean add(@RequestBody User user) {
        return userService.addUser(user);
    }


    @RequestMapping("/changepass")
    public String change(String password) {
        System.out.println(dataSource.toString());
        dataSource.setPassword(password);
        try {
            dataSource.restart();
            dataSource.init();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return dataSource.toString();
    }


}
